package dyyx.util;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dyyx.dto.WebResult;

public abstract class JsonWebUtil {

	private static final Set<String> OPS = new HashSet<>();

	private static final String OP_FORMAT = "format";
	private static final String OP_CHECK = "check";
	
	private static final String OP_yaml2properties = "yaml2properties";
	private static final String OP_properties2yaml = "properties2yaml";



	static {
		

		OPS.add(OP_FORMAT);
		OPS.add(OP_CHECK);
		
		OPS.add(OP_yaml2properties);
		OPS.add(OP_properties2yaml);


	}
	
	

	public static void run(HttpServletRequest request, WebResult webResult) throws Exception {
		try {
			run_(request, webResult);
		} catch (Throwable e) {
			webResult.msg = webResult.op + " error," + e;
		}
	}
	
	

	private static void run_(HttpServletRequest request, WebResult webResult) throws Exception {
		String op = WebUtil.get(request, "op");
		String content = WebUtil.get(request, "content");
		

		if (StringUtils.isBlank(op)) {
			webResult.msg = "op blank";
			return;
		}
		if (!OPS.contains(op)) {
			webResult.msg = "op error";
			return;
		}
		if (StringUtils.isBlank(content)) {
			webResult.msg = "content blank";
			return;
		}
		
		
		webResult.op = op;

		if (OP_FORMAT.equals(op)) {

			JSONObject json = JSON.parseObject(content);
			String str = FastjsonUtil.toString(json, true);

			webResult.msg = str;

			return;
		}

		if (OP_CHECK.equals(op)) {

			try {
			    JSONObject json = JSON.parseObject(content);
			    String str = json.toString();
				webResult.msg = "check ok";

			}catch(Throwable e) {
				webResult.msg = "check error,"+e;
			}


			return;
		}
		
		
		if (OP_yaml2properties.equals(op)) {

			 
			String str = TransferUtil.yml2properties(content);

			webResult.msg = str;

			return;
		}
		
		if (OP_properties2yaml.equals(op)) {

			
			String str = TransferUtil.properties2yaml(content);


			webResult.msg = str;

			return;
		}
		
		

		
		throw new Exception("op error,"+op);


	}
	
	

}
